package com.developer.platform.domain.scheduler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.developer.platform.domain.NoticeAggregateRoot;
import com.developer.platform.domain.Systems;
import com.developer.platform.domain.repository.INoticeRepository;
import com.developer.platform.domain.service.IQuartzJobService;
import com.developer.platform.infrastructure.data.mapper.SystemMapper;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Objects;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

/**
 * 通知定时任务
 *
 * @author ：qiaoliang
 * @date ：2021-01-07
 */
@Component
public class NoticeOnlineQuartzJob implements Job  {

  private final INoticeRepository noticeRepository;
  private final IQuartzJobService quartzJobService;
  private final SystemMapper systemMapper;

  public NoticeOnlineQuartzJob(
      INoticeRepository noticeRepository,
      IQuartzJobService quartzJobService,
      SystemMapper systemMapper) {
    this.noticeRepository = noticeRepository;
    this.quartzJobService = quartzJobService;
    this.systemMapper = systemMapper;
  }

  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
    Object jobId = jobDataMap.get("id");
    if(Objects.isNull(jobId)){
      return;
    }
    long id = Long.parseLong((String)jobId);
    NoticeAggregateRoot noticeAggregateRoot = noticeRepository.findById(id);
    if(Objects.nonNull(noticeAggregateRoot)){
      List<Systems> systemsList = this.systemMap(noticeAggregateRoot.getSystemIds());
      if(CollUtil.isNotEmpty(systemsList)){
        systemsList.forEach(systems -> {
          if(StrUtil.isNotBlank(systems.getTriggerUrl())){
            HttpUtil.get(systems.getTriggerUrl());
          }
        });
      }
      quartzJobService.close((String)jobDataMap.get("jobName"), (String)jobDataMap.get("subgroup"));
    }
  }

  /**
   *  通过系统ID查询系统名称
   *
   * @author ：qiaoliang
   * @param ids : 系统id
   * @return java.util.Map<java.lang.String, java.lang.String>
   * @date 2020-11-12 14:12
   */
  public List<Systems> systemMap(List<Long> ids){
    if(CollUtil.isEmpty(ids)){
      return Lists.newArrayList();
    }
    return systemMapper.selectBatchIds(ids);
  }

}
